package tools;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author malguy-wang sir
 * @create ---
 */
//替换httpServlet
public class baseServlet extends HttpServlet {
    //根据url最后一段进行请求分发(/xxx/*)

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求路径
        String uri = req.getRequestURI();
        //获取最后一段,是方法名
        String methodName = uri.substring(uri.lastIndexOf('/') + 1);
        //反射获取类,这里的this代表当前继承这个父类的子类
        Class<? extends baseServlet> aClass = this.getClass();
        //获取类的方法,此时方法都需要有req和resp形参
        try {
            Method method = aClass.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //执行方法
    }
}
